<template>
  <el-select placeholder="请选择所属机构" size="small" v-model="company.val" @change="companyChange">
    <el-option v-for="item in company.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
  </el-select>
</template>

<script lang="ts">
import { defineComponent, reactive, onMounted } from 'vue';
import { useStore } from 'vuex';
/**
 * 机构选择组件封装
 * @Author yuanyexu
 * @Date 2021-08-19
 */
export default defineComponent({
  name: 'CompanyChoose',
  props: ['defaultVal'],
  emits: ['selected'],
  setup(props, ctx) {
    const store = useStore();
    const company = reactive({
      val: '',
      list: []
    });
    // 默认初始值
    company.val = props.defaultVal;
    company.list = store.state.company.companyList;
    const companyChange = (data) => {
      ctx.emit('selected', data);
    };
    const getcompanyList = async() => {
      if (company.list.length === 0) {
        await store.dispatch('company/getList');
        company.list = store.state.company.companyList;
      }
    }
    onMounted (() => {
      getcompanyList();
    })
    return {
      company,
      companyChange
    };
  },
});
</script>
